import socket
import os


class FileClient():
    def __init__(self,ls):
        self.ls = ls
        self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.conn.connect(("127.0.0.1", 6789))
            print("TCP服务器连接成功")
        except ConnectionError:
            print("服务器没有启动")

    def send_request(self):
        # self.ls = str(["wordcloud", "15133854715", "17849327316"]).encode("utf-8")
        print(self.ls)
        self.conn.send(str(self.ls).encode("utf-8"))

    def rev_pic(self):
        path = str(self.ls[2])+".png"
        w = open(path, 'wb')
        while True:
            rec = self.conn.recv(1024)
            print(rec)
            try:
                cache = rec.decode("utf-8")
                if cache == "finish" or not rec:
                    print('发送完成')
                    self.conn.close()
                    break
            except UnicodeDecodeError:
                w.write(rec)
        w.close()
        return os.path.join(os.getcwd(),path)


if __name__ == '__main__':
    f1 = FileClient()
    f1.send_request()
    f1.rev_pic()